package tests;

import common.Utils;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class GamePage extends Utils {
    public static String url = "http://8.156.68.126:8080/game_room.html";

    public GamePage() {
        super(url);
    }

    //检查页面是否可以正常打开
    public void checkPageRight() throws InterruptedException {
        //检查棋盘是否加载成功
//        driver.findElement(By.cssSelector("#chess"));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#chess")));
        //检查行棋日志
//        driver.findElement(By.cssSelector("#screen"));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#screen")));

    }

    // 第二个玩家主动退出游戏
    public void gameOver() throws InterruptedException {
        Thread.sleep(1200);
        try {
            // 确保 secondDriver 已初始化
            if (secondDriver != null) {
                secondDriver.navigate().back();
//                secondWait.until(ExpectedConditions.urlContains("game_hall"));
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 确保无论如何都会关闭 secondDriver
            if (secondDriver != null) {
                secondDriver.quit();
                secondDriver = null; // 清除引用
                Thread.sleep(500);
            }
        }
    }

    // 主玩家返回对战大厅--结算
    public void victory() {
        try {
            assert driver.getCurrentUrl().contains("game_room");

            Thread.sleep(1200);

            // 等待游戏结束条件（根据实际游戏逻辑调整）
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("body > div.container > div > button")));

            // 点击结算按钮
            driver.findElement(By.cssSelector("body > div.container > div > button")).click();

            // 等待返回大厅
            wait.until(ExpectedConditions.urlContains("game_hall"));

            // 检查积分变化
            String nowScore = driver.findElement(By.cssSelector("#user-stats > div:nth-child(2) > span.stat-value")).getText();
            assert !(nowScore.equals(initScore));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭主 driver
            if (driver != null) {
                driver.quit();
                driver = null; // 清除引用
            }
        }
    }
}
